package com.blb.http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 自定义Http服务器
 */
public class MyHttpServer {

    /**
     * 服务器端口
     */
    public static final int PORT = 666;

    /**
     * 服务器文件目录
     */
    public static final String SERVER_DIR = "D:\\home\\";

    /**
     * 启动服务器
     */
    public void start(){
        System.out.println("启动http服务器");
        //启动服务器socket
        try (ServerSocket serverSocket = new ServerSocket(PORT);){
            while(true){
                try {
                    //接收客户端
                    Socket client = serverSocket.accept();
                    //读取请求报文
                    StringBuilder stringBuilder = new StringBuilder();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        stringBuilder.append(line);
                        System.out.println(line);
                        if (line.length() == 0) {
                            break;
                        }
                    }
                    System.out.println("xxx");
                    //解析报文中的URL
                    String[] strs = stringBuilder.toString().split(" ");
                    String url = strs[1];
                    //获得本地的html文件
                    StringBuilder stringBuilder2 = new StringBuilder();
                    BufferedReader reader2 = new BufferedReader(new InputStreamReader(new FileInputStream(SERVER_DIR + url)));
                    String line2 = null;
                    while ((line2 = reader2.readLine()) != null) {
                        stringBuilder2.append(line2);
                        System.out.println(line2);
                    }
                    //编写响应报文
                    StringBuilder responseText = new StringBuilder();
                    responseText.append("HTTP/1.1 200 OK\r\n");
                    responseText.append("Content-Type: text/html; charset=UTF-8\r\n");
                    responseText.append("\r\n");
                    responseText.append(stringBuilder2);
                    //向客户端发送响应报文
                    OutputStream outputStream = client.getOutputStream();
                    outputStream.write(responseText.toString().getBytes());
                    outputStream.flush();
                    outputStream.close();
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MyHttpServer().start();
    }
}
